package com.zhiwei.codesecurity.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64;

import com.zhiwei.codesecurity.common.constants.GlobalConstant;
import com.zhiwei.codesecurity.common.enums.EncryptedModel;

public class AESSupport {

    /**
     * 生成AES秘钥
     *
     * @param bitLength
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String generateAESKey(int bitLength) throws NoSuchAlgorithmException {
        if (bitLength == GlobalConstant.AES_KEY_128_BIT)
            return RandomNumUtil.generateRandomNum(16);
        else if (bitLength == GlobalConstant.AES_KEY_192_BITS)
            return RandomNumUtil.generateRandomNum(24);
        else if (bitLength == GlobalConstant.AES_KEY_256_BIT)
            return RandomNumUtil.generateRandomNum(32);
        return null;
    }


    /**
     * AES加密
     *
     * @param data 加密数据
     * @param key  加密密钥
     * @return 返回Base64编码后的字符串
     */
    public static String encrypt(String data, String key) {
        try {
            //byte[] byteKey = Hex.decodeHex(key.toCharArray());
            byte[] byteKey = key.getBytes();
            byte[] byteData = data.getBytes("UTF-8");
            System.out.println("byteData=" + new String(byteData, "utf-8"));
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, EncryptedModel.AES.getModeName());
            Cipher cipher = Cipher.getInstance(EncryptedModel.AES_CIPHER_ALGORITHM.getModeName());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] result = cipher.doFinal(byteData);
            return Base64.encodeBase64String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * AES解密
     *
     * @param data 需要解密的数据
     * @param key  解密密钥
     * @return
     */
    public static String decrypt(String data, String key) {
        try {
            //Base64做编码
            // byte[] byteKey = Hex.decodeHex(key.toCharArray());
            byte[] byteKey = key.getBytes();
            byte[] byteData = Base64.decodeBase64(data);
            SecretKeySpec keySpec = new SecretKeySpec(byteKey, EncryptedModel.AES.getModeName());
            Cipher cipher = Cipher.getInstance(EncryptedModel.AES_CIPHER_ALGORITHM.getModeName());
            cipher.init(Cipher.DECRYPT_MODE, keySpec);
            byte[] result = cipher.doFinal(byteData);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {

        /**
         String key = "a208545d1061f9f0"; // 生产 ： 52a73d2dd1850aa5
         String data = "{\"code\":\"0\",\"data\":{\"address\":\"广东省****20楼2号\",\"commissionRate\":\"40.0000\",\"companyName\":\"深圳市****有限公司\",\"contractNo\":\"20180101006666\",\"creditorNo\":\"ZQ201803202018444761693\",\"creditorRightsNo\":\"BFQB20171211000006\",\"debtorCity\":\"深圳市\",\"debtorProvince\":\"广东\",\"entrustEndTime\":\"2018/03/20\",\"entrustStartTime\":\"2018/03/29\",\"gender\":\"男\",\"id\":564488926430230016,\"identity\":\"510000********8000\",\"identityAddress\":\"湖南省****5楼503\",\"mobile\":\"152****8888\",\"name\":\"周*沐\",\"repaymentTime\":\"2018/03/29\",\"resourcesList\":[],\"state\":{\"amount\":\"\",\"commission\":\"\",\"holding\":0,\"remainTime\":0,\"status\":4},\"totalAmount\":\"22.00\",\"workplace\":\"深圳市****有限公司\",\"workplaceAddress\":\"广东省深圳市****有限公司\",\"workplacePhone\":\"075****8888\"},\"msg\":\"成功\",\"serverTime\":1523191430840}";
         String encryptStr = encrypt(data, key);
         System.out.println(encryptStr);

         String encryptData = "L7yrDthEoteLLwH+DEh8aAsy5/g6Chu80aZ25+I4IMbxPFk6XmRTcyVsFTf9y98RNTgBfmB/dO0XhKQPsaA2NqaD/abREvEnh2iwyuKLJJ0OFkGm2ZG1Z+Fa8JcCK4QSHAPbVsiXrnqz3ABwjE+DwRdan5mQK3qFi00GrDIuHjn7+G6pmkhdqKhpgH0O/PJUGF8zeqFJIDnTz6H5rx8v1vHgwncUrXSxYRm05w7cnz+yVYsS19/1sbF+CllBwy3IbdKc2XZP0bRUAoQwda+YBj+DwyNplfNUMxUuEoDuhiGpXfJyezir7aeCYiQE4G9hsLqQJ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88RB5vPI4S9xrpl4Q+3hDEtfX0uvMwWxzmC3odyUm9p9gEmNTdM1ikRF1UaOaII71RBQ+KilVugmDTvfM02FywBH9JKKskg==";

         System.out.println(":::::====>>>" + decrypt(encryptStr, key));

         **/



        String key = generateAESKey(GlobalConstant.AES_KEY_128_BIT);
        String encryptStr = encrypt("你好", key);
        System.out.println(key);
        System.out.println(encryptStr);
        System.out.println(decrypt(encryptStr, key));


    }
}
